//
//  MyorderVC.m
//  YaoHeAPP
//
//  Created by xyh on 16/3/30.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MyorderVC.h"
#import "Masonry.h"

#import "Controller.h"

#import "SVPullToRefresh.h"


#import "labelview.h"

#import "orderHeaderView.h"

#import "orderfooterView.h"

#import "MyOrderData.h"
#import "MyorderDataList.h"

#import "orderCell.h"


#import "TongYong.h"


#import "moneybuyCV.h"

#import "GeneraldetailsVC.h"


#import "NOstuDetailVC.h"

#import "TWOstuDetailsVC.h"

#import "HKDetailsVC.h"

#import "Tool.h"

#import "OrderDetailesVC.h"

#import "ProvinceAndCity.h"

#import "NSString+formatWithFloat.h"

#define bgVCcolor [UIColor colorWithRed:235.f/255.f green:235.f/255.f blue:244.f/255.f alpha:1]
#define Color153  [UIColor colorWithRed:80.f/255.f green:80.f/255.f blue:80.f/255.f alpha:1]
#define screenWidth self.view.frame.size.width
#define screenHeight self.view.frame.size.height

@interface MyorderVC ()<UITableViewDelegate,UITableViewDataSource,labelviewdelegate,moneybuyCVdelgaet>
{
    NSMutableArray *arrayList;//总数组
 
    NSMutableArray *orderCellArray;//内部表格
    
    labelview *la;

    
    NSMutableArray *totalLastTime;
    
    NSTimer *timer;
    
    
    NSInteger quxiaosectionbut;
    
     NSString*city_ID,*sheng_ID;

    NSInteger orderlistNum;
    
}
@property(nonatomic,strong) UITableView *tableview;
@property (nonatomic, assign)NSInteger  page;//页数
@end

@implementation MyorderVC

//视图将要消失的时候将定时器关闭
- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    
    if (timer.isValid) {
        [timer invalidate];
    }
    timer = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"MyorderVC"];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"MyorderVC"];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //注册一个通知监听通知过来的操作
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(upallorderview) name:@"allorderlist" object:nil];

    
    self.navigationController.navigationBar.hidden=YES;
    
    self.view.backgroundColor=bgVCcolor;
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    //    navcBar.frame=CGRectMake(0, 0, screenWidth, 60);
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(kNavigationBarHeight);  make.right.offset(0);
    }];
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"全部订单";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    //    titleLabel.frame=CGRectMake(self.view.frame.size.width/2-70, 25, 140, 30);
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(self.view.frame.size.width/2-70);
        make.width.offset(140);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton*leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    //    leftButton.frame=CGRectMake(6, 60-6-28, 30, 28);
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(24);
        make.height.offset(22);
        make.bottom.offset(-12);
    }];

    
    //定义数组
    arrayList=[[NSMutableArray alloc]init];
    orderCellArray=[[NSMutableArray alloc]init];
    totalLastTime=[[NSMutableArray alloc]init];
    //创建表格
    _tableview=[[UITableView alloc]initWithFrame:CGRectMake(0,kNavigationBarHeight, self.view.frame.size.width, self.view.frame.size.height-kNavigationBarHeight) style:UITableViewStyleGrouped];
    
    _tableview.backgroundColor= [UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
    _tableview.delegate=self;
    _tableview.dataSource=self;
    _tableview.separatorStyle=NO;
   
    [self.view addSubview:_tableview];
    
    
    //放置下拉上拉刷新控件
    __weak MyorderVC *weakSelf = self;
    
    // setup pull-to-refresh
    [self.tableview addPullToRefreshWithActionHandler:^{
        [weakSelf insertRowAtTop];
    }];
    
    // setup infinite scrolling
    [self.tableview addInfiniteScrollingWithActionHandler:^{
        [weakSelf insertRowAtBottom];
    }];
    
    [self insertRowAtTop];


    
}
//通知返回刷心动额数据
-(void)upallorderview
{

    [self insertRowAtTop];
    
}


-(void)insertRowAtTop {
    __weak MyorderVC *weakSelf = self;
    
    [weakSelf.tableview beginUpdates];
    
    _page=0;
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    [dic setValue:@"0" forKey:@"page_num"];
    [dic setValue:@"10" forKey:@"page_step"];
    [dic setValue:@"" forKey:@"member_id"];
    
    [Controller requestWithURL:GETORDERLIST jsondic:dic finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            
            [arrayList removeAllObjects];
            
            [arrayList addObjectsFromArray:data.data[@"data"]];
            
            [totalLastTime removeAllObjects];
            
            
            for (int i=0; i<arrayList.count; i++) {
                
                 MyOrderData *ordered=[[MyOrderData alloc]initWith:arrayList[i]];
                
                 NSInteger status=ordered.status.integerValue;
                if (status==10) {
                    
                    NSString *miaost=arrayList[i][@"expired_time"];
                    NSInteger miao=miaost.integerValue/1000;
                    if (miao>0) {
                        
                        NSString *stm=[NSString stringWithFormat:@"%ld",(long)miao];
                        
                        NSDictionary *dic = @{@"indexPath":[NSString stringWithFormat:@"%i",i],@"lastTime":stm};
                        [totalLastTime addObject:dic];

                    }else{
                        
                        NSMutableDictionary *arraydic=[[NSMutableDictionary alloc]init];
                        
                        arraydic=[arrayList[i] mutableCopy];
                        
                        NSNumber*number1=[NSNumber numberWithInteger:-1];

                        [arraydic setObject:number1 forKey:@"status"];
                        
                        [arrayList replaceObjectAtIndex:i withObject:arraydic];
                        
                        
                    }
                    
                   
                }
                
                
            }
            
            

            //判断 是否  有 无数据
            if (arrayList.count==0) {
                if (la) {
                    [la removeFromSuperview];
                }
                la=[[labelview alloc]init];
                [la setimage:@"dingdanNew" tit:@"空荡荡的，什么也没有" buttontit:@"去购物" frem:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
                la.backgroundColor= [UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
                la.image.frame=CGRectMake((self.view.frame.size.width-100)/2, 50, 100, 133);
                la.label.frame=CGRectMake(50, 193, self.view.frame.size.width-100, 30);
                la.button.frame=CGRectMake(40, 233, self.view.frame.size.width-80, 40);
                la.delegate=self;
                [_tableview addSubview:la];
                
                
            }else{
                
                if (la) {
                    [la removeFromSuperview];
                }
                [self.tableview reloadData];
                
                if (totalLastTime.count>0) {
                    
                    [self startTimer];
                }

                
            }
            
        }
        else
        {
            
        }
    }];
    
    
    // 3. 结束刷新(相当于动画)
    [weakSelf.tableview endUpdates];
    
    [weakSelf.tableview.pullToRefreshView stopAnimating];

    
}


- (void)insertRowAtBottom {
    
    __weak MyorderVC *weakSelf = self;
    
    [weakSelf.tableview beginUpdates];
    
    _page=_page+1;
    NSNumber*number1=[NSNumber numberWithInteger:_page];
    NSNumber*number2=[NSNumber numberWithInteger:10];
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    [dic setValue:number1 forKey:@"page_num"];
    [dic setValue:number2 forKey:@"page_step"];
    [dic setValue:@"" forKey:@"member_id"];

    [Controller requestWithURL:GETORDERLIST jsondic:dic finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            [arrayList addObjectsFromArray:data.data[@"data"]];
            
            
            for (int i=0; i<arrayList.count; i++) {
                
                MyOrderData *ordered=[[MyOrderData alloc]initWith:arrayList[i]];
                
                NSInteger status=ordered.status.integerValue;
                if (status==10) {
                    
                    NSString *miaost=arrayList[i][@"expired_time"];
                    NSInteger miao=miaost.integerValue/1000;
                
                    if (miao>0) {
                        
                        NSString *stm=[NSString stringWithFormat:@"%ld",(long)miao];
                        
                        NSDictionary *dic = @{@"indexPath":[NSString stringWithFormat:@"%i",i],@"lastTime":stm};
                        [totalLastTime addObject:dic];
                        
                    }else{
                    
                        NSMutableDictionary *arraydic=[[NSMutableDictionary alloc]init];
                        arraydic=arrayList[i];
                        
                        [arraydic setObject:@"-1" forKey:@"status"];
                        
                        [arrayList replaceObjectAtIndex:i withObject:arraydic];
                        
                    
                    }
                    
                }
                
            }

            [self.tableview reloadData];
            if (totalLastTime.count>0) {
                
                [self startTimer];
            }

            
            
        }
        else
        {
            
        }
    }];
    
    [weakSelf.tableview endUpdates];
    [weakSelf.tableview.infiniteScrollingView stopAnimating];
    
    
}


//去购物按钮代理（无数据的时候）
- (void)didClickButtonInBottomView{
    RootTabBarViewController *rootTabBarViewController = [RootTabBarViewController rootViewController];
    [rootTabBarViewController changeRootViewControllerTo:3];
    
}


#pragma mark ------------开启定时器方法--------
//开启定时器方法：
- (void)startTimer
{
    if (timer.isValid) {
        [timer invalidate];
    }
    timer=nil;
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshLessTime) userInfo:@"" repeats:YES];
    
    //    如果不添加下面这条语句，在UITableView拖动的时候，会阻塞定时器的调用
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
    
}

//主要的定时器中的方法，在该方法中，遍历totalLastTime，取出其中保存的lasttime和indexpath，time用来显示，在显示完后自减，indexpath代表对应显示的位置，在一次循环后，将新的time和没有改变的indexpath从新替换totalLastTime 中对应位置的元素，以此保证每一秒执行时，显示time都是最新的。
- (void)refreshLessTime
{
    NSInteger time;
    for (int i = 0; i < totalLastTime.count; i++) {
        time = [[[totalLastTime objectAtIndex:i] objectForKey:@"lastTime"] integerValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:[[[totalLastTime objectAtIndex:i] objectForKey:@"indexPath"] integerValue]];
        
        if (time<=0) {
            //刷新并移除过时的数据
            [self insertRowAtTop];
            
        }else{
            
            orderfooterView *footview = (orderfooterView *)[_tableview footerViewForSection:indexPath.section];
            NSString *ss=[NSString stringWithFormat:@"截止时间:%@",[self lessSecondToDay:--time]];
            NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:ss];
            NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:@":"].location+1,noteStr.length-5 );
            [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];
            [footview.jiezhiTime setAttributedText:noteStr] ;
            
            NSDictionary *dic = @{@"indexPath": [NSString stringWithFormat:@"%li",(long)indexPath.section],@"lastTime": [NSString stringWithFormat:@"%lu",(unsigned long)time]};
            [totalLastTime replaceObjectAtIndex:i withObject:dic];
            
        }
        
        
    }
}

- (NSString *)lessSecondToDay:(NSUInteger)seconds
{
    //    NSUInteger day  = (NSUInteger)seconds/(24*3600);
    NSUInteger hour = (NSUInteger)(seconds%(24*3600))/3600;
    NSUInteger min  = (NSUInteger)(seconds%(3600))/60;
    NSUInteger second = (NSUInteger)(seconds%60);
    
    NSString *time = [NSString stringWithFormat:@"%lu:%lu:%lu",(unsigned long)hour,(unsigned long)min,(unsigned long)second];
    return time;
    
}





#pragma  mark--------------表格代理方法-----------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return arrayList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    MyOrderData *order=[[MyOrderData alloc]initWith:arrayList[section]];
    
    return order.pro_data.count;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //指定cellIdentifier为自定义的cell
    static NSString *CellIdentifier = @"orderCell";
    
    //取出对应段落的数据
    MyOrderData *order3=[[MyOrderData alloc]initWith:arrayList[indexPath.section]];
    
    MyorderDataList *orderListData=[[MyorderDataList alloc]initWith:order3.pro_data[indexPath.row]];
    
    //自定义cell类
    orderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //无色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (cell == nil) {
        //通过xib的名称加载自定义的cell
        cell = [[[NSBundle mainBundle] loadNibNamed:@"orderCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
//    4.1.1订单列表：展示货品参数
//    展示购买的货品：
//    型材 、管材 ： 品类（如扁钢等）、 材质、 规格、形状（如方管、圆管等，客户没有上传就不展示）、重量（总重）、数量、所在地、产地；
//    卷、板、带：材质、表面、 规格(厚度*宽度*长度） 参厚 等级 重量（总重） 仓库、产地；
    
    
    //顶部字符串拼接
    NSString *toplable;
    if ([TongYong isBlankObjectAndStr:orderListData.suface_code]) {
        toplable=[NSString stringWithFormat:@"%@ %@",orderListData.category_name,orderListData.material_code];
    }else{
        toplable=[NSString stringWithFormat:@"%@ %@/%@",orderListData.category_name,orderListData.material_code,orderListData.suface_code];
        
    }

    
    
    NSString *guige=orderListData.spec_code;
    
    //参厚
    NSString *canhou;
    if ([TongYong isBlankObjectAndStr:orderListData.reference_thick ]) {
        canhou=@"";
    }else{
        canhou=[NSString stringWithFormat:@"(%@)",orderListData.reference_thick];
    }
    
    //边部
    NSString *bianbu;
    if ([TongYong isBlankObjectAndStr:orderListData.edge_name ]) {
        bianbu=@"";
    }else{
        
        bianbu=[NSString stringWithFormat:@"/%@",orderListData.edge_name];
        
    }
    
    //等级
    NSString *dengji;
    if ([TongYong isBlankObjectAndStr:orderListData.level_name ]) {
        
        dengji=@"";
        
    }else{
        
        dengji=[NSString stringWithFormat:@"/%@",orderListData.level_name];
        
    }
    
    
    //包装
    NSString *baozhuang;
    if ([TongYong isBlankObjectAndStr:orderListData.package_type ]) {
        
        baozhuang=@"";
        
    }else{
        //包装类型//(30,"裸包"),(10,"简包"),(20,"精包"),(0,"正常包装")
        NSInteger typ=orderListData.package_type.integerValue;
        if (typ==30) {
            baozhuang=[NSString stringWithFormat:@"/裸包"];
        }else if(typ==20){
            baozhuang=[NSString stringWithFormat:@"/精包"];
        }else if(typ==10){
            baozhuang=[NSString stringWithFormat:@"/简包"];
        }else{
            
            baozhuang=[NSString stringWithFormat:@"正常包装"];
        }
    }
    
    
    //形状
    NSString *xinzhuang;
    if ([TongYong isBlankObjectAndStr:orderListData.shape_name ]) {
        
        xinzhuang=@"";
        
    }else{
        
        xinzhuang=[NSString stringWithFormat:@"/%@",orderListData.shape_name];
        
    }
    
    //品名
    NSString *pingming;
    if ([TongYong isBlankObjectAndStr:orderListData.category_name ]) {
        
        pingming=@"";
        
    }else{
        
        pingming=[NSString stringWithFormat:@"/%@",orderListData.category_name];
        
    }
    
    
    

    //单位类型
    NSInteger unitpric=orderListData.price_unit.integerValue;
    
    //并且计算出金额
    //计算金额
    //单位类型
    NSString *QUANTITY=[NSString stringWithFormat:@"%@",orderListData.quantity];
    NSString *weight=[NSString stringWithFormat:@"%@",orderListData.weight];
//    NSString *sale_price=[NSString stringWithFormat:@"%@",orderListData.DISCOUNT_PRICE];
    
    NSDecimalNumber *quantityDM = [[NSDecimalNumber alloc] initWithString:QUANTITY];//个数
    NSDecimalNumber *weightDM = [[NSDecimalNumber alloc] initWithString:weight];//单个重量
    
    NSDecimalNumber *zongweightDM=[[NSDecimalNumber alloc]initWithString:@"0"];
    
    NSString *weightName=@"";
    
if (order3.source_flag.integerValue==0) {
    if (unitpric==10) {
        //元每吨
        NSDecimalNumber *qian = [[NSDecimalNumber alloc] initWithString:@"1000"];
        zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
        zongweightDM=[zongweightDM decimalNumberByDividingBy:qian];
        weightName=[NSString stringWithFormat:@"/%@吨/%ld",[NSString notRounding:zongweightDM afterPoint:3],(long)orderListData.quantity.integerValue];
    } else if (unitpric==20||unitpric==40) {
        //支或张
        zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
        weightName=[NSString stringWithFormat:@"/%@千克/%ld",[NSString notRounding:zongweightDM afterPoint:3],(long)orderListData.quantity.integerValue];
    } else {
        //千克
        zongweightDM = [quantityDM decimalNumberByMultiplyingBy:weightDM];
        weightName=[NSString stringWithFormat:@"/%@千克/%ld",[NSString notRounding:zongweightDM afterPoint:3],(long)orderListData.quantity.integerValue];
    }
}
    NSString *bigTEXT;
    if ([orderListData.category_name isEqualToString:@"板"]||[orderListData.category_name isEqualToString:@"卷"]||[orderListData.category_name isEqualToString:@"板材"]||[orderListData.category_name isEqualToString:@"卷材"]) {
        //		板卷   规格(参厚)/边部/等级/包装
        
        bigTEXT=[NSString stringWithFormat:@"%@  %@%@%@%@%@%@",toplable,guige,canhou,bianbu,dengji,weightName,baozhuang];
        
        
    }else{
        
        bigTEXT=[NSString stringWithFormat:@"%@  %@%@%@%@%@%@%@",toplable,guige,pingming,xinzhuang,bianbu,dengji,weightName,baozhuang];
    }

    cell.bigLable.text=bigTEXT;
    
    
    //仓库  生产商
    NSString *ck;
    if ([TongYong isBlankObjectAndStr:orderListData.house_name ]) {
        
        ck=@"";
        
    }else{
        
        ck=[NSString stringWithFormat:@"%@",orderListData.house_name];
        
    }
    
    NSString *scs;
    if ([TongYong isBlankObjectAndStr:orderListData.manufacturer_name ]) {
        
        scs=@"";
        
    }else{
        
        scs=[NSString stringWithFormat:@"%@",orderListData.manufacturer_name];
        
    }
    
    NSString *geshu;
    if ([TongYong isBlankObjectAndStr:orderListData.quantity]) {
        
        geshu=@"";
        
    }else{
        
        NSString *dan;
        //单位
        if ([orderListData.category_name isEqualToString:@"卷"]||[orderListData.category_name isEqualToString:@"卷材"]||[orderListData.category_name isEqualToString:@"带"]||[orderListData.category_name isEqualToString:@"带材"]) {
            dan=@"个";
        }else if([orderListData.category_name isEqualToString:@"板"]||[orderListData.category_name isEqualToString:@"板材"]){
            
            dan=@"张";
            
        }else if([orderListData.category_name isEqualToString:@"管"]||[orderListData.category_name isEqualToString:@"管材"]){
            
            dan=@"支";
            
        }else if([orderListData.category_name isEqualToString:@"型"]||[orderListData.category_name isEqualToString:@"型材"]){
            
            dan=@"个";
            
        } else {
            dan = @"";
        }
        geshu = [NSString stringWithFormat:@"%@%@", orderListData.quantity, dan];
    }
    

    //判断是哪来的订单
    if (order3.source_flag.integerValue==0) {
        //现货订单号
        cell.addandhous.text=[NSString stringWithFormat:@"%@    %@",ck,scs];
        
    } else {
        //求购询单号
        
        sheng_ID=orderListData.supply_province_id;
        city_ID =orderListData.supply_city_id;
        NSString*City=[ProvinceAndCity inputCityID:city_ID];
        NSString*Sheng=[ProvinceAndCity inputShengID:sheng_ID];
        cell.addandhous.text=[NSString stringWithFormat:@"%@%@    %@",Sheng,City,geshu];
    
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
   MyOrderData *orderdetail=[[MyOrderData alloc]initWith:arrayList[indexPath.section]];

    NSMutableArray *pro_dataArray=[[NSMutableArray alloc]init];
    pro_dataArray=orderdetail.pro_data;
    
    NSString *statustr;
    //判断是哪来的订单
    if (orderdetail.source_flag.integerValue==0) {
        //现货订单号
        NSInteger status=orderdetail.status.integerValue;
        if (status==10) {
            statustr=@"待支付";
            
            TWOstuDetailsVC *generalVC=[[TWOstuDetailsVC alloc]init];
            generalVC.intent_order_id=orderdetail.intent_order_id;
            generalVC.isdaizhifu=@"全部订单列表";
            [self.navigationController pushViewController:generalVC animated:YES];
            
            
        }else if(status==15){
            
            statustr=@"已付定金";
            
            HKDetailsVC *generalVC=[[HKDetailsVC alloc]init];
            generalVC.order_ids=orderdetail.sale_order_id;
            generalVC.ordernum=1;
            generalVC.num=[NSString stringWithFormat:@"%lu",(unsigned long)pro_dataArray.count];
            [self.navigationController pushViewController:generalVC animated:YES];

            
            
        }else if(status==20){
            
//            statustr=@"已结算";
            //结算详情
            GeneraldetailsVC *generalVC=[[GeneraldetailsVC alloc]init];
            generalVC.intent_order_id=orderdetail.intent_order_id;
            [self.navigationController pushViewController:generalVC animated:YES];
            
            
        }else if(status==-1){
//            statustr=@"已失效";
            
            NOstuDetailVC *generalVC=[[NOstuDetailVC alloc]init];
            generalVC.intent_order_id=orderdetail.intent_order_id;
            [self.navigationController pushViewController:generalVC animated:YES];
            
            
        }else if(status==40){
//            statustr=@"已退款";
            
            NOstuDetailVC *generalVC=[[NOstuDetailVC alloc]init];
            generalVC.intent_order_id=orderdetail.intent_order_id;
            [self.navigationController pushViewController:generalVC animated:YES];
            
            
        }
        
        
    }else{
    
        //进入详情页面
        
        OrderDetailesVC *detailsVC=[OrderDetailesVC new];
        NSString *orderid=orderdetail.sale_order_id;
        detailsVC.orderID=orderid;
        [self.navigationController pushViewController:detailsVC animated:YES];

    }
}

#pragma mark -----------------设置段头段尾--------------------------
//区头高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
//返回区头View
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MyOrderData *order2=[[MyOrderData alloc]initWith:arrayList[section]];
    
    
    orderHeaderView *headView=[[orderHeaderView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 40)];
    
    headView.contentView.backgroundColor=[UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];

    NSString *stheaderla;
     NSString *statustr;
    //判断是哪来的订单
    if (order2.source_flag.integerValue==0) {
        //现货订单号
        stheaderla=[NSString stringWithFormat:@"%@",order2.intent_order_code];
        NSInteger status=order2.status.integerValue;
       
        if (status==10) {
            statustr=@"待支付";
        }else if(status==15){
            statustr=@"已付定金";
            headView.yanqifukuanimg.image=[UIImage imageNamed:@"yanqifukuan"];
        }else if(status==20){
            statustr=@"已结算";
        }else if(status==-1){
            statustr=@"已失效";
        }else if(status==40){
            statustr=@"已退款";
        }
    
        
    }else{
        //求购订单号
        stheaderla=[NSString stringWithFormat:@"%@",order2.intent_order_code];
        NSInteger reportStatus=order2.report_status.integerValue;
        
        //判断状态进行状态兑换
        if (reportStatus==-1) {
            //质检取消
            statustr=@"质检取消";
            
        }else if(reportStatus==0)
        {   //质检中
            statustr=@"质检中";
           
        }else if(reportStatus==10)
        {
            //质检完成
            statustr=@"质检完成";
            
        }else if(reportStatus==5)
        {
            //质检申请中
            statustr=@"质检申请中";
            
        }

    }
    
    headView.companyorderlabel.text=stheaderla;
    headView.orderstaylabel.text=statustr;
    return headView;
}

//用区尾当分割
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 34;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    
    MyOrderData *order4=[[MyOrderData alloc]initWith:arrayList[section]];

    orderfooterView *footerView=[[orderfooterView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 34)];
    
    footerView.contentView.backgroundColor=[UIColor whiteColor];
    
    //判断是哪来的订单
    if (order4.source_flag.integerValue==0) {
        //现货订单号
    
        NSInteger status=order4.status.integerValue;
        
        if (status==10) {
//            statustr=@"待支付";
//            （取消订单）（去支付）
            footerView.leftbutton.layer.borderWidth=1;
            footerView.leftbutton.layer.borderColor=[UIColor colorWithRed:193/255.0 green:193/255.0 blue:193/255.0  alpha:1].CGColor;
            footerView.leftbutton.backgroundColor=[UIColor whiteColor];
            footerView.leftbutton.tag=10000+section;
            [footerView.leftbutton setTitle:@"取消订单" forState:UIControlStateNormal];
            footerView.leftbutton.titleLabel.font=[UIFont systemFontOfSize:14];
            [footerView.leftbutton setTitleColor:[UIColor colorWithRed:80/255.0 green:84/255.0 blue:85/255.0  alpha:1] forState:UIControlStateNormal];
            [footerView.leftbutton addTarget:self action:@selector(leftbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            
            
            footerView.rightbutton.backgroundColor=[UIColor colorWithRed:251/255.0 green:87/255.0 blue:60/255.0  alpha:1];
            [footerView.rightbutton setTitle:@"去支付" forState:UIControlStateNormal];
            footerView.rightbutton.tag=20000+section;
            footerView.rightbutton.titleLabel.font=[UIFont systemFontOfSize:14];
            [footerView.rightbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [footerView.rightbutton addTarget:self action:@selector(rightbuttonAction:) forControlEvents:UIControlEventTouchUpInside];

            
            
            
        }else if(status==15){
//            statustr=@"已付定金";
//            （联系售后）（支付尾款）
            
            footerView.leftbutton.layer.borderWidth=1;
            footerView.leftbutton.layer.borderColor=[UIColor colorWithRed:193/255.0 green:193/255.0 blue:193/255.0  alpha:1].CGColor;
            footerView.leftbutton.backgroundColor=[UIColor whiteColor];
            footerView.leftbutton.tag=10000+section;
            [footerView.leftbutton setTitle:@"联系售后" forState:UIControlStateNormal];
            footerView.leftbutton.titleLabel.font=[UIFont systemFontOfSize:14];
            [footerView.leftbutton setTitleColor:[UIColor colorWithRed:80/255.0 green:84/255.0 blue:85/255.0  alpha:1] forState:UIControlStateNormal];
            [footerView.leftbutton addTarget:self action:@selector(leftbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            
            footerView.rightbutton.backgroundColor=[UIColor colorWithRed:251/255.0 green:87/255.0 blue:60/255.0  alpha:1];
            [footerView.rightbutton setTitle:@"支付尾款" forState:UIControlStateNormal];
            footerView.rightbutton.tag=20000+section;
            footerView.rightbutton.titleLabel.font=[UIFont systemFontOfSize:14];
            [footerView.rightbutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [footerView.rightbutton addTarget:self action:@selector(rightbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            
        }else if(status==20){
//            statustr=@"已结算";
//            （删除订单）  （联系售后）
//            footerView.leftbutton.layer.borderWidth=1;
//            footerView.leftbutton.layer.borderColor=[UIColor colorWithRed:193/255.0 green:193/255.0 blue:193/255.0  alpha:1].CGColor;
//            footerView.leftbutton.backgroundColor=[UIColor whiteColor];
//            footerView.leftbutton.tag=10000+section;
//            [footerView.leftbutton setTitle:@"删除订单" forState:UIControlStateNormal];
//            footerView.leftbutton.titleLabel.font=[UIFont systemFontOfSize:14];
//            [footerView.leftbutton setTitleColor:[UIColor colorWithRed:80/255.0 green:84/255.0 blue:85/255.0  alpha:1] forState:UIControlStateNormal];
//            [footerView.leftbutton addTarget:self action:@selector(leftbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            
            footerView.rightbutton.layer.borderWidth=1;
            footerView.rightbutton.layer.borderColor=[UIColor colorWithRed:193/255.0 green:193/255.0 blue:193/255.0  alpha:1].CGColor;
            footerView.rightbutton.backgroundColor=[UIColor whiteColor];
            [footerView.rightbutton setTitle:@"联系售后" forState:UIControlStateNormal];
            footerView.rightbutton.tag=20000+section;
            footerView.rightbutton.titleLabel.font=[UIFont systemFontOfSize:14];
            [footerView.rightbutton setTitleColor:[UIColor colorWithRed:80/255.0 green:84/255.0 blue:85/255.0  alpha:1] forState:UIControlStateNormal];
            [footerView.rightbutton addTarget:self action:@selector(rightbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            
            
        }else if(status==-1){
//            statustr=@"已失效";
//            （删除订单）
//            footerView.rightbutton.layer.borderWidth=1;
//            footerView.rightbutton.layer.borderColor=[UIColor colorWithRed:193/255.0 green:193/255.0 blue:193/255.0  alpha:1].CGColor;
//            footerView.rightbutton.backgroundColor=[UIColor whiteColor];
//            [footerView.rightbutton setTitle:@"删除订单" forState:UIControlStateNormal];
//            footerView.rightbutton.tag=20000+section;
//            footerView.rightbutton.titleLabel.font=[UIFont systemFontOfSize:14];
//            [footerView.rightbutton setTitleColor:[UIColor colorWithRed:80/255.0 green:84/255.0 blue:85/255.0  alpha:1] forState:UIControlStateNormal];
//            [footerView.rightbutton addTarget:self action:@selector(rightbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
            
            
            
        }else if(status==40){
//            statustr=@"已退款";
//            （退款明细）（删除订单）
//            footerView.leftbutton.layer.borderWidth=1;
//            footerView.leftbutton.layer.borderColor=[UIColor colorWithRed:193/255.0 green:193/255.0 blue:193/255.0  alpha:1].CGColor;
//            footerView.leftbutton.backgroundColor=[UIColor whiteColor];
//            footerView.leftbutton.tag=10000+section;
//            [footerView.leftbutton setTitle:@"退款明细" forState:UIControlStateNormal];
//            footerView.leftbutton.titleLabel.font=[UIFont systemFontOfSize:14];
//            [footerView.leftbutton setTitleColor:[UIColor colorWithRed:80/255.0 green:84/255.0 blue:85/255.0  alpha:1] forState:UIControlStateNormal];
//            [footerView.leftbutton addTarget:self action:@selector(leftbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
//            
//            
//            footerView.rightbutton.layer.borderWidth=1;
//            footerView.rightbutton.layer.borderColor=[UIColor colorWithRed:193/255.0 green:193/255.0 blue:193/255.0  alpha:1].CGColor;
//            footerView.rightbutton.backgroundColor=[UIColor whiteColor];
//            [footerView.rightbutton setTitle:@"删除订单" forState:UIControlStateNormal];
//            footerView.rightbutton.tag=20000+section;
//            footerView.rightbutton.titleLabel.font=[UIFont systemFontOfSize:14];
//            [footerView.rightbutton setTitleColor:[UIColor colorWithRed:80/255.0 green:84/255.0 blue:85/255.0  alpha:1] forState:UIControlStateNormal];
//            [footerView.rightbutton addTarget:self action:@selector(rightbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
//            
          
            
        }

        
    }else{
       //求购订单号
    
//        NSInteger reportStatus=order4.report_status.integerValue;
        
//        //判断状态进行状态兑换
//        if (reportStatus==-1) {
//            //质检取消
////            statustr=@"质检取消";
//            
//            
//        }else if(reportStatus==0)
//        {   //质检中
////            statustr=@"质检中";
//            
//            
//        }else if(reportStatus==10)
//        {    //质检完成
////            statustr=@"质检完成";
//            
//        }else if(reportStatus==5)
//        {
//            //质检申请中
////            statustr=@"质检申请中";
//            
//        }

        
        footerView.rightbutton.layer.borderWidth=1;
        footerView.rightbutton.layer.borderColor=[UIColor colorWithRed:193/255.0 green:193/255.0 blue:193/255.0  alpha:1].CGColor;
        footerView.rightbutton.backgroundColor=[UIColor whiteColor];
        [footerView.rightbutton setTitle:@"联系售后" forState:UIControlStateNormal];
        footerView.rightbutton.tag=20000+section;
        footerView.rightbutton.titleLabel.font=[UIFont systemFontOfSize:14];
        [footerView.rightbutton setTitleColor:[UIColor colorWithRed:80/255.0 green:84/255.0 blue:85/255.0  alpha:1] forState:UIControlStateNormal];
        [footerView.rightbutton addTarget:self action:@selector(rightbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        
    
    }
    
    
    return footerView;

}


#pragma mark------------尾部按钮事件-----------------
//左边按钮事件
-(void)leftbuttonAction:(UIButton *)leghtbut
{
    NSInteger tagbut=leghtbut.tag;
    
    NSInteger butsection=tagbut-10000;
   
    MyOrderData *order5=[[MyOrderData alloc]initWith:arrayList[butsection]];

    //判断是哪来的订单
    if (order5.source_flag.integerValue==0) {
        //现货订单号
        NSInteger status=order5.status.integerValue;
        
        if (status==10) {
//            statustr=@"待支付";    （取消订单）
            [self quxiaoorder:butsection];
            
        }else if(status==15){
//            statustr=@"已付定金";（联系售后）
            [self callshouhou:butsection];
            
        }else if(status==20){
//            statustr=@"已结算";  （删除订单）
            [self deleteorder:butsection];
            
        }else if(status==-1){
//            statustr=@"已失效";
        }else if(status==40){
//            statustr=@"已退款";   （退款明细）
            [self tuikuanmingxi:butsection];
            
        }
        
        
    }else{
        //求购订单号
        NSInteger reportStatus=order5.report_status.integerValue;
        
        //判断状态进行状态兑换
        if (reportStatus==-1) {
            //质检取消
        }else if(reportStatus==0)
        {   //质检中
        }else if(reportStatus==10)
        {
            //质检完成
        }else if(reportStatus==5)
        {
            //质检申请中

        }
        
    }

    
    

}

//右边按钮事件
-(void)rightbuttonAction:(UIButton *)rightbut
{
    NSInteger tagbut=rightbut.tag;
    
    NSInteger butsection=tagbut-20000;

    
    MyOrderData *order6=[[MyOrderData alloc]initWith:arrayList[butsection]];
    
    //判断是哪来的订单
    if (order6.source_flag.integerValue==0) {
        //现货订单号
        NSInteger status=order6.status.integerValue;
        
        if (status==10) {
            //            statustr=@"待支付";     （去支付）
            [self quzhifu:butsection];
            
        }else if(status==15){
            //            statustr=@"已付定金";    （支付尾款）
            [self zhifuweikuan:butsection];
            
        }else if(status==20){
            //            statustr=@"已结算";     （联系售后）
            [self callshouhou:butsection];
            
        }else if(status==-1){
            //            statustr=@"已失效";     （删除订单）
            [self deleteorder:butsection];
            
        }else if(status==40){
            //            statustr=@"已退款";      （删除订单）
            [self deleteorder:butsection];
        }
        
        
    }else{
        //求购订单号
        NSInteger reportStatus=order6.report_status.integerValue;
        
        //判断状态进行状态兑换
        if (reportStatus==-1) {
            //质检取消
            //            statustr=@"质检取消";
            
        }else if(reportStatus==0)
        {   //质检中
            //            statustr=@"质检中";
            
            
        }else if(reportStatus==10)
        {
            //质检完成
            //            statustr=@"质检完成";
            
        }else if(reportStatus==5)
        {
            //质检申请中
            //            statustr=@"质检申请中";
            
        }
        
    }

    
}

//取消订单
-(void)quxiaoorder:(NSInteger )sectionbut
{
    
    quxiaosectionbut=sectionbut;
    
    //初始化AlertView
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"取消订单"
                                                    message:@"订单取消后无法恢复，确定要取消订单吗？"
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定",nil];
    
    //这个属性继承自UIView，当一个视图中有多个AlertView时，可以用这个属性来区分
    alert.tag = 4;
    //只读属性，看AlertView是否可见
    [alert show];

    


}
//根据被点击按钮的索引处理点击事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag==4){
        
        if (buttonIndex==1) {
            //取消订单
            
            MyOrderData *order7=[[MyOrderData alloc]initWith:arrayList[quxiaosectionbut]];
            
            NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
            [dic setValue:order7.intent_order_id forKey:@"intent_order_id"];
            [Controller requestWithURL:CANCELORDER jsondic:dic finishBlock:^(ClassData* data) {
                if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
                {
                    //刷新列表
                    [self insertRowAtTop];
                    
                }
                else
                {
                    
                }
            }];

            
        }
    
     }
    
    
}

//去支付
-(void)quzhifu:(NSInteger )sectionbut
{
    [MobClick event:@"quanbudingdan_dangezhifu"];
    
    MyOrderData *order7=[[MyOrderData alloc]initWith:arrayList[sectionbut]];
    moneybuyCV *moneyvc=[[moneybuyCV alloc]init];
    moneyvc.pay_type=@"10";
    moneyvc.intent_order_id=order7.intent_order_id;
    moneyvc.ordernum=1;
    moneyvc.delegate=self;
    //获取当前时间值
    NSTimeInterval timest = [[NSDate date] timeIntervalSince1970];
    NSInteger timeintage=timest;
    NSString *sttime=order7.expired_time;
    NSInteger extime=sttime.integerValue/1000;
    NSInteger timevely=timeintage+extime;
    moneyvc.odertime=[NSString stringWithFormat:@"%ld",(long)timevely];
    [self.navigationController pushViewController:moneyvc animated:YES];

    
}
//支付成功刷新界面
-(void)uporderlist
{
    
  [self insertRowAtTop];

}

//去支付尾款
-(void)zhifuweikuan:(NSInteger )sectionbut
{
    [MobClick event:@"quanbudingdan_zhifuweikuan"];
    
    MyOrderData *order7=[[MyOrderData alloc]initWith:arrayList[sectionbut]];
    moneybuyCV *moneyvc=[[moneybuyCV alloc]init];
    moneyvc.pay_type=@"5";
    moneyvc.ordernum=1;
    moneyvc.intent_order_id=order7.intent_order_id;
    moneyvc.order_ids=order7.sale_order_id;
    [self.navigationController pushViewController:moneyvc animated:YES];

    
}

//联系售后
-(void)callshouhou:(NSInteger )sectionbut
{
    //进入打电话页面
    UIWebView *webview = [[UIWebView alloc] init];
    [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel:4008850054"]]];
    [self.view addSubview:webview];
    
}

//删除订单
-(void)deleteorder:(NSInteger )sectionbut
{

   
    
}

//退款明细
-(void)tuikuanmingxi:(NSInteger )sectionbut
{


    
}


-(void)backLogin
{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
